// pages/oldQRcode/oldQRocde.js
const util = require('../../utils/util.js')
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    info: {},
    src: '../images/background.jpg',
    color: '#808080',
    share: true,
    colorState: true,
    canvasSrc: '../images/background.jpg',
    colorList: [
      '#B3B3B3', '#B2DFEE', '#B23AEE', '#B22222',
      '#B0E2FF', '#B0E0E6', '#B0C4DE', '#B0B0B0',
      '#B03060', '#AEEEEE', '#ADFF2F', '#ADD8E6',
      '#FFFFFF', '#FFFFF0', '#FFFFE0 ', '#FFFF00 ',
      '#FFFAFA', '#FFFAF0', '#FFFACD', '#FFF8DC',
      '#FFF68F', '#FFF5EE', '#FFF0F5', '#FFEFDB',
      '#FFEFD5', '#FFEC8B', '#FFEBCD', '#FFE7BA',
      '#FFE4E1', '#FFE4C4', '#FFE4B5', '#FFE1FF',
      '#FFDEAD', '#FFDAB9', '#FFD700', '#FFD39B',
      '#FFC1C1', '#FFC125', '#FFC0CB', '#FFBBFF',
      '#FFB90F', '#FFB6C1', '#FFB5C5', '#FFAEB9',
      '#FFA54F', '#FFA500', '#FFA07A', '#FF8C69',
      '#FF8C00', '#FF83FA', '#FF82AB', '#FF8247',
      '#FF7F50', '#FF7F24', '#FF7F00', '#FF7256',
      '#FF6EB4', '#FF6A6A', '#FF69B4', '#FF6347',
      '#FF4500', '#FF4040', '#FF3E96', '#FF34B3',
      '#FF3030', '#FF1493', '#FF00FF', '#FF0000',
      '#FDF5E6', '#FCFCFC', '#FAFAFA', '#FAFAD2',
      '#FAF0E6', '#FAEBD7', '#FA8072', '#F8F8FF',
      '#F7F7F7', '#F5FFFA', '#F5F5F5', '#F5F5DC',
      '#F5DEB3', '#F4F4F4', '#F4A460', '#F2F2F2',
      '#F0FFFF', '#F0FFF0', '#F0F8FF', '#F0F0F0',
      '#F0E68C', '#F08080', '#EEEEE0', '#EEEED1',
      '#EEEE00', '#EEE9E9', '#EEE9BF', '#EEE8CD',
      '#EEE8AA', '#EEE685', '#EEE5DE', '#EEE0E5',
      '#EEDFCC', '#EEDC82', '#EED8AE', '#EED5D2',
      '#EED5B7', '#EED2EE', '#EECFA1', '#EECBAD',
      '#EEC900', '#EEC591', '#EEB4B4', '#EEB422',
      '#EEAEEE', '#EEAD0E', '#EEA9B8', '#EEA2AD',
      '#EE9A49', '#EE9A00', '#EE9572', '#EE82EE',
      '#EE8262', '#EE7AE9', '#EE799F', '#EE7942',
      '#EE7621', '#EE7600', '#EE6AA7', '#EE6A50',
      '#EE6363', '#EE5C42', '#EE4000', '#EE3B3B',
      '#EE3A8C', '#EE30A7', '#EE2C2C', '#EE1289',
      '#EE00EE', '#EE0000', '#EDEDED', '#EBEBEB',
      '#EAEAEA', '#E9967A', '#E8E8E8', '#E6E6FA',
      '#E5E5E5', '#E3E3E3', '#E0FFFF', '#E0EEEE',
      '#E0EEE0', '#E0E0E0', '#E066FF', '#DEDEDE',
      '#DEB887', '#DDA0DD', '#DCDCDC', '#DC143C',
      '#DBDBDB', '#DB7093', '#DAA520', '#DA70D6',
      '#D9D9D9', '#D8BFD8', '#D6D6D6', '#D4D4D4',
      '#D3D3D3', '#D2B48C', '#D2691E', '#D1EEEE',
      '#D1D1D1', '#D15FEE', '#D02090', '#CFCFCF',
      '#CDCDC1', '#CDCDB4', '#CDCD00', '#CDC9C9',
      '#CDC9A5', '#CDC8B1', '#CDC673', '#CDC5BF',
      '#CDC1C5', '#CDC0B0', '#CDBE70', '#CDBA96',
      '#CDB7B5', '#CDB79E', '#CDB5CD', '#CDB38B',
      '#CDAF95', '#CDAD00', '#CDAA7D', '#CD9B9B',
      '#CD9B1D', '#CD96CD', '#CD950C', '#CD919E',
      '#CD8C95', '#CD853F', '#CD8500', '#CD8162',
      '#CD7054', '#CD69C9', '#CD6889', '#CD6839',
      '#CD661D', '#CD6600', '#CD6090', '#CD5C5C',
      '#CD5B45', '#CD5555', '#CD4F39', '#CD3700',
      '#CD3333', '#CD3278', '#CD2990', '#CD2626',
      '#CD1076', '#CD00CD', '#CD0000', '#CCCCCC',
      '#CAFF70', '#CAE1FF', '#C9C9C9', '#C7C7C7',
      '#C71585', '#C6E2FF', '#C67171', '#C5C1AA',
      '#C4C4C4', '#C2C2C2', '#C1FFC1', '#C1CDCD',
      '#C1CDC1', '#C1C1C1', '#C0FF3E', '#BFEFFF',
      '#BFBFBF', '#BF3EFF', '#BEBEBE', '#BDBDBD',
      '#BDB76B', '#BCEE68', '#BCD2EE', '#BC8F8F',
      '#BBFFFF', '#BABABA', '#BA55D3', '#B9D3EE',
      '#B8B8B8', '#B8860B', '#B7B7B7', '#B5B5B5',
      '#B4EEB4', '#B4CDCD', '#B452CD', '#B3EE3A', '#808080'
    ],
    // font_family: ['微软雅黑', '仿宋', '楷体'],
    colorBor: '#808080',
    family: '微软雅黑'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(app)
    let res = wx.getSystemInfoSync()
    console.log(res)
    this.setData({
      windowHeight: res.windowHeight - 1,
      windowWidth: res.windowWidth,
      label: options.label,
      tiem: app.nickname + '邀请你一起与时光 call'
    })
  },

  canvasIdErrorCallback: function(e) {
    console.error(e.detail.errMsg)
  },


  /**
   * 绘制图片
   */
  drawInit: function(info) {
    wx.showLoading({
      title: '加载中...',
      duration: 1500
    })
    var contentTitle = info.title;
    var contentStr = info.intro;
    var that = this
    var res = wx.getSystemInfoSync();
    var canvasWidth = res.windowWidth * 0.9;
    // 获取canvas的的宽  自适应宽（设备宽/750) px
    var Rpx = (canvasWidth / 375).toFixed(2);
    //画布高度 -底部按钮高度
    var canvasHeight = res.windowHeight * 0.9;
    // 使用 wx.createContext 获取绘图上下文 context
    var context = wx.createCanvasContext('secondCanvas')
    //设置行高
    var lineHeight = Rpx * 30;
    //左边距
    var paddingLeft = Rpx * 20;
    //右边距
    var paddingRight = Rpx * 20;
    //当前行高
    var currentLineHeight = Rpx * 20;

    context.setGlobalAlpha(0.8)
    //高度减去 图片高度
    console.log(that.data.canvasSrc)
    context.drawImage(that.data.canvasSrc, 0, 0, canvasWidth, canvasHeight); //默认背景图
    //标题内容颜色默认
    context.fillStyle = "rgba(255,255,255,0.5)";
    context.fillRect(0, 0, canvasWidth, canvasHeight); //默认背景色
    //设置标题
    var resultTitle = breakLinesForCanvas(context, contentTitle, canvasWidth - paddingLeft - paddingRight, `${(Rpx * 17).toFixed(0)}px PingFangSC-Regular`);
    console.log(resultTitle)
    //字体颜色
    context.fillStyle = '#1da6ee';
    resultTitle.forEach(function(line, index) {
      currentLineHeight += Rpx * 15;
      context.fillText(line, paddingLeft, currentLineHeight);
    });
    //画分割线
    currentLineHeight += Rpx * 15;
    context.setLineDash([Rpx * 6, Rpx * 3.75]);
    context.moveTo(paddingLeft, currentLineHeight);
    context.lineTo(canvasWidth - paddingRight, currentLineHeight);
    context.strokeStyle = '#808080';
    context.stroke();
    //设置内容
    var result = breakLinesForCanvas(context, contentStr || '无内容', canvasWidth - paddingLeft - paddingRight, `${(Rpx * 17).toFixed(0)}px PingFangSC-Regular`);
    console.log(result);
    //字体颜色
    context.fillStyle = that.data.color;
    result.forEach(function(line, index) {
      currentLineHeight += Rpx * 30;
      context.fillText(line, paddingLeft, currentLineHeight);
    })
    const grd = context.createCircularGradient(canvasWidth - 35, canvasHeight - 30, 300)
    grd.addColorStop(0.5, '#fff')
    grd.addColorStop(1, 'rgba(255,255,255,0.3)')
    context.setFillStyle(grd)
    context.fillRect(0, canvasHeight - 60, canvasWidth, canvasHeight)
    context.fill()
    context.fillStyle = '#808080';
    context.setFontSize(15)
    context.fillText(app.nickname + "邀请你一起与时光 call", paddingLeft, canvasHeight - (canvasHeight - (canvasHeight - 50)) / 2);
    // 自己画图（备用动态二维码）
    context.beginPath();
    context.arc(canvasWidth - 35, canvasHeight - 30, ((canvasWidth - 10) - (canvasWidth - 60)) / 2, 0, Math.PI * 2, false);
    context.setFillStyle('#fff')
    context.fill()
    context.clip();
    // //圆形切割-结束
    context.drawImage('../images/qrcode.jpg', canvasWidth - 60, canvasHeight - 55, (canvasWidth - 10) - (canvasWidth - 60), (canvasHeight - 10) - (canvasHeight - 60));
    context.draw();
  },

  share(e) {
    const self = this
    const val = e.detail.value.content
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#010101',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
    if (val == '') {
      wx.showToast({
        title: '写点心得吧！',
        image: '../images/erorr.png'
      })
    } else {
      let info = {
        "title": "标 签： #" + self.data.label + "#",
        "intro": val
      };
      self.setData({
        share: !self.data.share,
        info
      });
      self.drawInit(info);
    }
  },

  colortab: function(e) {
    this.setData({
      colorBor: e.currentTarget.dataset.color,
      color: e.currentTarget.dataset.color
    })
  },


  family: function(e) {
    this.setData({
      family: e.currentTarget.dataset.family
    })
  },

  saveImg: function() {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'secondCanvas',
      fileType: 'jpg',
      success: function(res) {
        console.log(res) // 返回图片路径
        wx.showLoading({
          title: '保存中...',
          mask: true
        });
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(res) {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail: function(res) {
            wx.hideLoading()
            console.log(res)
          }
        })
      }
    })
  },

  upImg: function() {
    const _this = this
    util.upImg(function(r, temp) {
      let data = r.data
      console.log(data)
      let a = JSON.parse(data)
      _this.setData({
        src: 'https://fly.zwstar.cc' + a.data.src,
        canvasSrc: temp
      })
    })
  },

  switchover: function() {
    this.setData({
      colorState: false
    })
  },

  hidd: function() {
    this.setData({
      colorState: true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: app.nickname + '邀请你一起与时光 call',
      path: '/pages/home/home'
    }
  }
})

function findBreakPoint(text, width, context) {
  var min = 0;
  var max = text.length - 1;
  while (min <= max) {
    var middle = Math.floor((min + max) / 2);
    var middleWidth = context.measureText(text.substr(0, middle)).width;
    var oneCharWiderThanMiddleWidth = context.measureText(text.substr(0, middle + 1)).width;
    if (middleWidth <= width && oneCharWiderThanMiddleWidth > width) {
      return middle;
    }
    if (middleWidth < width) {
      min = middle + 1;
    } else {
      max = middle - 1;
    }
  }

  return -1;
}

function breakLinesForCanvas(context, text, width, font) {
  var result = [];
  if (font) {
    context.font = font;
  }
  var textArray = text.split('\r\n');
  for (let i = 0; i < textArray.length; i++) {
    let item = textArray[i];
    var breakPoint = 0;
    while ((breakPoint = findBreakPoint(item, width, context)) !== -1) {
      result.push(item.substr(0, breakPoint));
      item = item.substr(breakPoint);
    }
    if (item) {
      result.push(item);
    }
  }
  return result;
}